/**
 * Copyright (c) 2011-2019, James Zhan 詹波 (jfinal@126.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.hinglo.ehcahe.plugin;

import com.jfinal.plugin.IPlugin;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;

import java.net.URL;

/**
 * EhCachePlugin.
 */
public class EhCachePlugin implements IPlugin {

    private static CacheManager cacheManager;
    private String configurationFileName;

    public EhCachePlugin() {

    }

    public EhCachePlugin(CacheManager cacheManager) {
        EhCachePlugin.cacheManager = cacheManager;
    }

    public EhCachePlugin(String configurationFileName) {
        this.configurationFileName = configurationFileName;
    }


    @Override
    public boolean start() {
        createCacheManager();
        CacheKit.init(cacheManager);
        return true;
    }

    private void createCacheManager() {
        if (cacheManager != null) {
            return;
        }
        String ehcacheName = "/ehcache.xml";
        if (configurationFileName == null) {
            configurationFileName = ehcacheName;
        }
        final URL myUrl = this.getClass().getResource(configurationFileName);
        Configuration xmlConfig = new XmlConfiguration(myUrl);
        cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
    }

    @Override
    public boolean stop() {
        cacheManager.close();
        cacheManager = null;
        return true;
    }
}




